<?php

namespace app\api\controller;

use think\Controller;
use think\Request;
\think\Loader::addNamespace('OAuth2', './extend/Oauth2');

class AuthController extends Controller
{
    private $service;
    protected function initialize()
    {
        $dsn      = 'mysql:dbname=new;host=119.29.22.178';
        $username = 'root';
        $password = 'xping0217';

    // error reporting (this is a demo, after all!)
        ini_set('display_errors',1);error_reporting(E_ALL);

    // Autoloading (composer is preferred, but for this example let's just do this)
//        require_once('oauth2/src/OAuth2/Autoloader.php');
        \OAuth2\Autoloader::register();

    // $dsn is the Data Source Name for your database, for exmaple "mysql:dbname=my_oauth2_db;host=localhost"
        $storage = new \OAuth2\Storage\Pdo(array('dsn' => $dsn, 'username' => $username, 'password' => $password));

    // Pass a storage object or array of storage objects to the OAuth2 server class
        $server = new \OAuth2\Server($storage);

    // Add the "Client Credentials" grant type (it is the simplest of the grant types)
        $server->addGrantType(new \OAuth2\GrantType\ClientCredentials($storage));

    // Add the "Authorization Code" grant type (this is where the oauth magic happens)
        $server->addGrantType(new \OAuth2\GrantType\AuthorizationCode($storage));

        $this->service = $server;
    }
    public function token(){
        $this->service->handleTokenRequest(\OAuth2\Request::createFromGlobals())->send();
    }

    public function token_validate(){
        if (!$this->service->verifyResourceRequest(\OAuth2\Request::createFromGlobals())) {
            return false;
        } else {
            return true;
        }
    }

    //PHPsession_id
    function sendCode() {
        $code = I ( 'code' );
        $param = [
            'appid' => "wx82334861d391b29a",
            'secret' => "faa01b24ccedd777fa577d1ee60700e6",
            'js_code' => $code,
            'grant_type' => 'authorization_code'
        ];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$param['appid']}&secret={$param['secret']}&js_code={$param['js_code']}&grant_type=authorization_code";
        // openid 用户唯一标识 session_key 会话密钥
        $data = post_data ( $url, [ ] ); // {"session_key":"gHkoobsIWnTYnUj1ZTQKDA==","expires_in":2592000,"openid":"onfcX0fV3mjzsLRK7C15vk_2N86w"}

        if ((isset ( $data ['errcode'] ) && $data ['errcode'] == '40029') || ! isset ( $data ['session_key'] ) || ! isset ( $data ['openid'] )) {
            return api_return ( 410001, [ ], '获取微信信息失败！' );
        } else {
            session ( 'session_key', $data ['session_key'] );
            session ( 'openid', $data ['openid'] );
            if (! M ( 'public_follow' )->where( array('openid'=>$data ['openid']))->find ())
            {
                $uid = M ( 'user' )->add ( [
                    'reg_time' => NOW_TIME
                ] );
                M ( 'public_follow' )->add ( [
                    'openid' => $data ['openid'],
                    'uid' => $uid
                ] );
            } else {
                $re = M ( 'public_follow' )->join ('weixin_user on weixin_public_follow.uid = weixin_user.uid' )->where (array('weixin_public_follow.openid'=>$data ['openid']))->find ();
                session ( 'user_info', $re );
                $uid = $re ['uid'];
            }

            session('mid',$uid);
            $return ['openid'] = $data ['openid'];
            $res = api_return ( 0, $return );

            echo $res;
        }
    }
}
